package com.cyy.learn.characterConverter

import com.cyy.util.RadixUtils
import org.apache.commons.codec.binary.Hex
import java.io.UnsupportedEncodingException


/**
 * @ClassName: CharacterConverterService
 * @Description: 编码转换工具
 * @author: xufeng
 * @date: 2018/1/25 14:49
 */

class CharacterConverterService {

    /**
     * 字符编码进制前缀字符填充 - 16进制.
     */
    @Throws(UnsupportedEncodingException::class)
    fun encode16RadixAddPrefix(input: String, charset: String, prefix: String): String {
        val sb = StringBuilder()
        for (i in 0 until input.length) {
            // ExCodec.encodeHex 转16进制
            sb.append(prefix).append(Hex.encodeHexString(input.substring(i, i + 1).toByteArray(charset(charset))))
        }
        return sb.toString()
    }

    /**
     * 字符编码进制前缀字符填充 - 10进制.
     */
    @Throws(UnsupportedEncodingException::class)
    fun encode10RadixAddPrefix(input: String, charset: String, prefix: String): String {
        val sb = StringBuilder()
        for (i in 0 until input.length) {
            sb.append(prefix).append(RadixUtils.convertRadixString16To10(Hex.encodeHexString(input.substring(i, i + 1).toByteArray(charset(charset)))))
        }
        return sb.toString()
    }

    /**
     * 字符编码进制前缀字符填充 - 8进制.
     */
    @Throws(UnsupportedEncodingException::class)
    fun encode8RadixAddPrefix(input: String, charset: String, prefix: String): String {
        val sb = StringBuilder()
        for (i in 0 until input.length) {
            sb.append(prefix).append(RadixUtils.convertRadixString16To8(Hex.encodeHexString(input.substring(i, i + 1).toByteArray(charset(charset)))))
        }
        return sb.toString()
    }

    /**
     * 字符编码进制前缀字符填充 - 2进制.
     */
    @Throws(UnsupportedEncodingException::class)
    fun encode2RadixAddPrefix(input: String, charset: String, prefix: String): String {
        val sb = StringBuilder()
        for (i in 0 until input.length) {
            sb.append(prefix).append(RadixUtils.convertRadixString16To2(Hex.encodeHexString(input.substring(i, i + 1).toByteArray(charset(charset)))))
        }
        return sb.toString()
    }
}